<template>
    <div class="search" :class="{'search-focus': isFocus}" v-click-outside="onClickOutside">
        <el-popover
            :visible="visible"
            placement="bottom"
            :show-arrow="false"
            :width="400"
            :teleported="false">
            <template #default>
                <search-history ></search-history>
                <search-discover></search-discover>
            </template>
            <template #reference>
                <div class="search-container" :class="{'search-focus': isFocus}">
                    <el-input
                        v-model="searchValue"
                        suffix-icon="Search"
                        placeholder="请输入内容"
                        @focus="searchFocus"
                        @input="searchInput">
                    </el-input>
                </div>
            </template>
        </el-popover>
    </div>
</template>

<script lang="ts" setup>
import searchHistory from './search-history.vue'
import searchDiscover from './search-discover.vue'
import { config } from '@/config'
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { ClickOutside as vClickOutside } from 'element-plus'
import { debounce } from 'throttle-debounce-ts'
import useStore from '@/store'
const { search } = useStore()
const { visible, isFocus } = storeToRefs(search)

const searchValue = ref<string>('')
const delay: number = config.animationDelay
const cssDelay: string = `${delay / 1000}s`

// 焦点
const searchFocus = () => {   
    search.setFocus(true)
    setTimeout(() => { search.setVisible(true) }, delay)
}
// 点击非气泡，气泡消失
const onClickOutside = () => {
    search.setVisible(false)
    setTimeout(() => { search.setFocus(false) }, delay)
}

// 输入查询并将内容保存到搜索历史中
const searchInput = debounce(delay, (val: string) => {
    if(!val) return    
    search.add(val)
    // TODO 查询
})
</script>

<style lang="less" scoped>
.transitionWidth {
    transition: width v-bind(cssDelay);
}
.search {
    line-height: 52px;
    margin-left: 15px;
    .search-container {
        width: 250px;
        .transitionWidth;
    }
    .search-focus {
        width: 400px;
        .el-input :deep(.el-input__wrapper){
            box-shadow: 0 0 0 1px var(--color-primary) inset;
        }
    }
}
</style>